package com.yanqu.road.dao.impl.player;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.triggerwindow.ActTriggerWindow;

import java.sql.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserActTriggerWindowDaoImpl extends TempDataObjectDao<ActTriggerWindow> {

    public ActTriggerWindow getUserActTriggerWindow(long userId) {
        ActTriggerWindow data = null;
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_act_trigger_window_user where userId=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(1, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                data = parse(rs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return data;
    }

    private static String addSql = "INSERT INTO t_u_act_trigger_window_user(userId,actIdList) VALUES(?,?)";

    @Override
    protected boolean addData(ActTriggerWindow data) {
        data.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getUserDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
        para.put(i++, new DbParameter(Types.VARCHAR, JSON.toJSONString(data.getActIdList())));
        if (getDb().executeNoneQuery(addSql, para) > 0) {
            return true;
        }
        return false;
    }

    private static String updateSql = "UPDATE t_u_act_trigger_window_user SET actIdList=? WHERE userId=?";

    @Override
    protected boolean updateData(ActTriggerWindow data) {
        data.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getUserDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.VARCHAR, JSON.toJSONString(data.getActIdList())));
        para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
        if (getDb().executeNoneQuery(updateSql, para) > 0) {
            return true;
        }
        return false;
    }

    @Override
    protected ActTriggerWindow parseData(ResultSet rs) throws SQLException {
        ActTriggerWindow data = new ActTriggerWindow();
        data.setUserId(rs.getLong("userId"));
        List<Integer> resultList = JSON.parseArray(rs.getString("actIdList"), Integer.class);
        data.setActIdList(resultList);
        return data;
    }
}
